package com.csun.cmny.mqtt.core;

import com.csun.cmny.mqtt.constant.MqttMsgConstants;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttMessage;

import net.sf.json.JSONObject;
import com.google.gson.JsonParseException;
import com.google.gson.JsonParser;

import java.util.Map;

/**
 * @Auther: chisj chisj@foxmal.com
 * @Date: 2019-01-15 15:13
 * @Description:
 */
@Slf4j
public class MqttClientSubCallback implements MqttCallback {

    private DeviceDataBase deviceData;

    /**
     * <p>Description: </p>
     * @param deviceDataBase
     */
    public MqttClientSubCallback(DeviceDataBase deviceDataBase) {
        // TODO Auto-generated constructor stub
        this.deviceData = deviceDataBase;
    }

    /* (non-Javadoc)
     * @see org.eclipse.paho.client.mqttv3.MqttCallback#connectionLost(java.lang.Throwable)
     */
    @Override
    public void connectionLost(Throwable t) {
        // TODO Auto-generated method stub
        System.out.println("sub 连接断开，可以做重连" + t.getLocalizedMessage());
    }

    /* (non-Javadoc)
     * @see org.eclipse.paho.client.mqttv3.MqttCallback#deliveryComplete(org.eclipse.paho.client.mqttv3.IMqttDeliveryToken)
     */
    @Override
    public void deliveryComplete(IMqttDeliveryToken token) {
        // TODO Auto-generated method stub
        System.out.println("deliveryComplete " + token.isComplete());
    }

    /**
     * 接收该主题的消息并处理
     * @param topic 接收消息主题
     * @param message 对应主题接收到的消息
     */
    @Override
    public void messageArrived(String topic, MqttMessage message) throws Exception {
        /* subscribe后得到的消息会执行到这里面 */
        String msg = new String(message.getPayload());

        log.info("接收消息主题 : " + topic);
        log.info("接收消息Qos: " + message.getQos());
        log.info("接收消息内容 : " + msg);

        try {
            new JsonParser().parse(msg);
        } catch (JsonParseException e) {
            System.out.println("bad json: " + new String(message.getPayload()));
            return ;
        }

        String msgType = parse(msg);
        if (null == msgType || "".equals(msgType)) {
            /* 设备消息错误 */
            System.out.println("消息错误 msg: " + msg);
            return ;
        }

        proccess(msgType, msg);
    }

    /**
     * @Description: 消息解析
     * @param @msg 要解析的消息
     * @param @return
     * @return String
     * @throws
     * @author chisj chisj@foxmail.com
     * @date 2017年10月11日
     */
    public String parse(String msg) {

        try {
            JSONObject  jasonObject = JSONObject.fromObject(msg);
            Map map = (Map)jasonObject;
            return (String)map.get("msgType");
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public void proccess(String msgType, String msg) {

        switch(msgType) {
            /* 数据上传 */
            case MqttMsgConstants.INVITE_UPLOAD :
                deviceData.deviceDataUpload(msg);
                break;
            /* 设备授权状态上传 */
            case MqttMsgConstants.INVITE_VALID :
                deviceData.deviceDataValid(msg);
                break;
            /* 设备开关机状态上传 */
            case MqttMsgConstants.INVITE_OPEN :
                deviceData.deviceDataOpen(msg);
                break;
            /* 设备警报信息上传 */
            case MqttMsgConstants.INVITE_ALERT :
                deviceData.deviceDataAlert(msg);
                break;
            /* 设备断线通知 */
            case MqttMsgConstants.INVITE_CLOSE :
                deviceData.deviceDataClose(msg);
                break;
            /* 报警器登录 */
            case MqttMsgConstants.PHONE_LOGIN :
                deviceData.phoneLogin(msg);
                break;
            case MqttMsgConstants.PHONE_CLOSE :
                deviceData.phoneClose(msg);
                break;
            case MqttMsgConstants.PHONE_EVENT :
                deviceData.phoneEvent(msg);
                break;
            case MqttMsgConstants.PHONE_HEAT :
                deviceData.phoneHeat(msg);
                break;
            case MqttMsgConstants.ACTUAL_DATA :
                deviceData.deviceDataActual(msg);
                break;
            case MqttMsgConstants.CONFIG_DATA :
                deviceData.deviceDataConfig(msg);
                break;
            case MqttMsgConstants.CTRL_DATA :
                deviceData.deviceDataCtrl(msg);
                break;
            case MqttMsgConstants.WARN_ERR :
                deviceData.deviceWarnErr(msg);
                break;
            case MqttMsgConstants.LOCATION :
                deviceData.deviceLocation(msg);
                break;
            case MqttMsgConstants.GATAWAY_BTN_MSG :
                deviceData.deviceGatewayButton(msg);
                break;
            case MqttMsgConstants.GATEWAY_BODY_MSG :
                deviceData.deviceGatewayBodySensor(msg);
                break;
            case MqttMsgConstants.SLEEP_BED_MSG :
                deviceData.deviceSleepBedMsg(msg);
                break;
            case MqttMsgConstants.SLEEP_BASIC_MSG :
                deviceData.deviceSleepBasicMsg(msg);
                break;
            case MqttMsgConstants.SLEEP_MSG :
                deviceData.deviceSleepMsg(msg);
                break;
            case MqttMsgConstants.SLEEP_ALARM_MSG :
                deviceData.deviceSleepAlarmMsg(msg);
                break;
            case MqttMsgConstants.SLEEP_CUR_VER_MSG :
                deviceData.deviceSleepCurVerMsg(msg);
                break;
            case MqttMsgConstants.SLEEP_UDT_VER_MSG :
                deviceData.deviceSleepUdtVerMsg(msg);
            default :
                System.out.println("未识别的消息：" + msg);
                break;
        }
    }

}
